// Created by WXX on 2021/11/29 11:55
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

/**
 * 执行用时：20 ms, 在所有 C++ 提交中击败了17.75%的用户
 * 内存消耗：9.8 MB, 在所有 C++ 提交中击败了54.31%的用户
 */
class Solution {
public:

    // 返回绝对值之差小于等于mid的数的个数
    int get(vector<int> &nums, int mid) {
        int res = 0;
        for (int i = 0, j = 0; i < nums.size(); i++) {
            while (nums[i] - nums[j] > mid) j++;
            res += i - j;
        }
        return res;
    }

    int smallestDistancePair(vector<int>& nums, int k) {
        sort(nums.begin(), nums.end());
        int l = 0, r = 1e6;
        while (l < r) {
            int mid = l + r >> 1;
            if (get(nums, mid) >= k) r = mid;
            else l = mid + 1;
        }
        return r;
    }
};

int main() {

    vector<int> nums = {1, 3, 1};
    cout << Solution().smallestDistancePair(nums, 1) << endl;  // 0

    return 0;
}
